package com.leyou.user.service.impl;

import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.NumberUtils;
import com.leyou.user.config.AmqpProperties;
import com.leyou.user.mapper.UserMapper;
import com.leyou.user.pojo.User;
import com.leyou.user.service.UserService;
import com.leyou.user.utils.CodecUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
@EnableConfigurationProperties(AmqpProperties.class)
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AmqpTemplate amqpTemplate;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private AmqpProperties prop;


    @Override
    public Boolean verifyUserPhoneAndName(String data, Integer type) {

        User user = new User();
        switch (type) {
            case 1:
                user.setUsername(data);
                break;
            case 2:
                user.setPhone(data);
                break;
            default:
                throw new LyException(ExceptionEnum.INVALID_DATA_TYPE);
        }

        int result = userMapper.selectCount(user);
        return result == 0;
    }

    @Override
    public void sendCode(String phone) {

        if (!phone.matches("^1[356789]\\d{9}$")) {
            throw new LyException(ExceptionEnum.INVALID_PHONE_NUMBER);
        }

        String generateCode = NumberUtils.generateCode(6);
        Map<String, String> map = new HashMap<>();
        map.put("phone", phone);
        map.put("code", generateCode);
        amqpTemplate.convertAndSend(prop.getExchange(), prop.getRoutingKey(), map);

        String key = prop.getKeyPrefix() + phone;
        redisTemplate.opsForValue().set(key, generateCode, 5, TimeUnit.MINUTES);
    }

    @Override
    public void register(User user, String code) {

        String key = prop.getKeyPrefix() + user.getPhone();
        String cacheCode = redisTemplate.opsForValue().get(key);

        if (!StringUtils.equals(cacheCode, code)) {
            throw new LyException(ExceptionEnum.INVALID_VERIFY_CODE);
        }

        String salt = CodecUtils.generateSalt();
        user.setSalt(salt);
        user.setPassword(CodecUtils.md5Hex(user.getPassword(), salt));

        user.setId(null);
        user.setCreated(new Date());

        int count = userMapper.insert(user);

        if (count != 1) {
            throw new LyException(ExceptionEnum.INTERNAL_SERVER_ERROR);
        }

        redisTemplate.delete(key);
    }

    @Override
    public User queryUserByUsernameAndPassword(String username, String password) {

        if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
            throw new LyException(ExceptionEnum.INVALID_USERNAME_PASSWORD);
        }

        User user = new User();
        user.setUsername(username);
        User queryUser = userMapper.selectOne(user);

        if (queryUser == null) {
            throw new LyException(ExceptionEnum.INVALID_USERNAME_PASSWORD);
        }

        if (!StringUtils.equals(queryUser.getPassword(), CodecUtils.md5Hex(password, queryUser.getSalt()))) {
            throw new LyException(ExceptionEnum.INVALID_USERNAME_PASSWORD);
        }
        return queryUser;
    }
}
